package com.foreknow.dao.inpl;

import com.foreknow.dao.GuestbookDao;
import com.foreknow.mapping.EntityMapping;
import com.foreknow.model.Guestbook;
import java.sql.SQLException;
import java.util.List;


public class GuestbookDaoImpl extends BaseDao implements GuestbookDao {

    @Override
    public List<Object> query() {
        //1. 链接数据库
//        DBManager dbManager= DBManager.getInstance();
//        Connection conn =dbManager.getConnection();
//        //2. 调用模板中JdbcTemplate中的方法query方法进行查询
//        JdbcTemplate jt =JdbcTemplate.getInstance();
//        //一定要调用JdbcTemplate的setConnection方法才能连接上数据库
//        jt.setConnection(conn);
        //3. 获取工厂类的队象.然后才能调用getMap方法根据key获取value值
//        MappingFactory ma = MappingFactory.getInstance();
        EntityMapping mapping = mappingFactory.getMap("GUEST_BOOKIMPL");//获取到Guestbook对象
        List<Object> list = jdbcTemplate.query("select * from Guestbook ", mapping);

        //3. 返回结果
        return list;
//        if (list.size()>0){
//            return (Guestbook) list.get(0);
//        }else {
//            return null;
//
//        }

    }

    //添加
    @Override
    public boolean add(Guestbook guestbook) throws SQLException {
        String sql = "insert into guestbook (name,phone) values (?,?)";
        int isRight = jdbcTemplate.update(sql, guestbook.getName(), guestbook.getPhone());
        return isRight == 1;
    }

    //删除
    @Override
    public boolean delete(int id) throws SQLException {
        String sql = "delete from guestbook where id=?";
        int delete = jdbcTemplate.update(sql, id);
        return delete == 1;
    }

    //修改
    @Override
    public boolean update(Guestbook guestbook) throws SQLException {

        String sql = "update guestbook set  name =? where id=?";
        int update = jdbcTemplate.update(sql, guestbook.getName(), guestbook.getId());
        return update == 1;
    }

    /**
     * 根据id查询
     * @param id
     * @return
     */
    @Override
    public Guestbook Idquery(int id) {
        EntityMapping mapping = mappingFactory.getMap("GUEST_BOOKIMPL");
        String sql = "select * from guestbook where id=?";
        List<Object> list = jdbcTemplate.query(sql, mapping, id);

        if (list.size() > 0) {
            return (Guestbook) list.get(0);
        } else {
            return null;

        }


    }

    /**
     * 练习修改方法
     * @param guestbook
     * @return
     * @throws SQLException
     */
    @Override
    public boolean updates(Guestbook guestbook) throws SQLException {
        String sql="update guestbook set name = ? where id=?";
        int updates=jdbcTemplate.update(sql,guestbook.getName(),guestbook.getId());
        return updates==1;
    }
}
